/*
 * Copyright 2008 Nathan C Jones
 * 
 * This file is part of Fivehundred.
 * 
 * Fivehundred is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * Fivehundred is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * Fivehundred. If not, see <http://www.gnu.org/licenses/>. 
 */

package com.googlecode.fivehundred.ui.simple;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JComponent;

import com.googlecode.fivehundred.model.Card;
import com.googlecode.fivehundred.model.CardCollection;
import com.googlecode.fivehundred.model.CardCollectionListener;
import com.googlecode.fivehundred.model.Hand;

/**
 * A visual display of a hand of cards.
 * 
 * @author Nathan C Jones
 */
public class JHand extends JComponent implements CardCollectionListener {

	private static final long serialVersionUID = 1L;

	/** The hand to be represented graphically. */
	private Hand playerHand;

	/** Internal mapping between cards and JCards. */
	private Map<Card, JCard> cards = new HashMap<Card, JCard>();

	public JHand(Hand playerHand) {
		this.playerHand = playerHand;
		playerHand.addCardCollectionListener(this);
		init();
	}

	private MouseListener mouseListener = new MouseAdapter() {
		@Override
		public void mousePressed(MouseEvent event) {
			if (event.getSource() instanceof JCard) {
				final JCard jCard = (JCard) event.getSource();
				new Thread(new Runnable() {
					public void run() {
						playerHand.remove(jCard.getCard());
					}
				}).start();
			}
		}
	};

	private void init() {
		setLayout(new CascadeLayout(25));
		for (Card card : playerHand) {
			addCard(card);
		}
	}

	private void addCard(Card card) {
		final JCard jCard = new JCard(card);
		jCard.addMouseListener(mouseListener);
		cards.put(card, jCard);
		add(jCard);
		validate();
		getParent().validate();
		repaint();
	}

	private void removeCard(Card card) {
		final JCard jCard = cards.get(card);
		if (jCard != null) {
			remove(jCard);
			cards.remove(card);
			getParent().validate();
			validate();
			repaint();
		}
	}

	@Override
	public void cardAdded(final Card card, CardCollection collection) {
		addCard(card);
	}

	@Override
	public void cardRemoved(final Card card, CardCollection collection) {
		removeCard(card);
	}
}
